package com.aipp.mall.h5.service;

import com.aipp.mall.common.exception.ServerException;
import com.aipp.mall.common.utils.SecurityUtil;
import com.aipp.mall.h5.domain.entity.MemberCart;
import com.aipp.mall.h5.domain.entity.Sku;
import com.aipp.mall.h5.domain.form.UpdateMemberCartForm;
import com.aipp.mall.h5.domain.vo.MemberCartVO;
import com.aipp.mall.h5.mapper.MemberCartMapper;
import com.aipp.mall.h5.mapper.SkuMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.dromara.hutool.core.collection.CollUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 购物车Service业务层处理
 *
 * @author zcc
 */
@Service
public class H5MemberCartService {

    @Resource
    private MemberCartMapper memberCartMapper;

    @Resource
    private SkuMapper skuMapper;

    /**
     * 查询购物车
     *
     * @param id 购物车主键
     * @return 购物车
     */
    public MemberCart selectById(Long id) {
        return memberCartMapper.selectById(id);
    }

    /**
     * 查询购物车列表
     */
    public List<MemberCartVO> cartList() {
        QueryWrapper<MemberCart> qw = new QueryWrapper<>();
        qw.eq("member_id", SecurityUtil.getMemberId());
        List<MemberCart> memberCartList = memberCartMapper.selectList(qw);
        if (CollUtil.isEmpty(memberCartList)) {
            return Collections.emptyList();
        }
        //查sku
        List<Long> skuIdList = memberCartList.stream().map(MemberCart::getSkuId).collect(Collectors.toList());
        QueryWrapper<Sku> skuQw = new QueryWrapper<>();
        skuQw.in("id", skuIdList);
        Map<Long, Sku> skuMap = skuMapper.selectList(skuQw).stream().collect(Collectors.toMap(Sku::getId, it -> it));
        List<MemberCartVO> resList = new ArrayList<>();
        memberCartList.forEach(item -> {
            MemberCartVO memberCartVO = new MemberCartVO();
            BeanUtils.copyProperties(item, memberCartVO);
            if (!skuMap.containsKey(item.getSkuId())) {
                memberCartVO.setStatus(0);
                memberCartVO.setSkuIfExist(0);
            } else {
                Sku sku = skuMap.get(item.getSkuId());
                memberCartVO.setPrice(sku.getPrice());
                memberCartVO.setSkuIfExist(1);
            }
            resList.add(memberCartVO);
        });
        return resList;
    }

    /**
     * 新增购物车
     *
     * @param memberCart 购物车
     * @return 结果
     */
    public int insert(MemberCart memberCart) {
        memberCart.setMemberId(SecurityUtil.getMemberId());
        //判断cart是否存在
        QueryWrapper<MemberCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", SecurityUtil.getMemberId());
        queryWrapper.eq("sku_id", memberCart.getSkuId());
        queryWrapper.eq("product_id", memberCart.getProductId());
        List<MemberCart> memberCarts = memberCartMapper.selectList(queryWrapper);
        if (CollUtil.isEmpty(memberCarts)) {
            memberCart.setStatus(1);
            memberCart.setCreateTime(LocalDateTime.now());
            memberCart.setCreateBy(SecurityUtil.getMemberId());
            return memberCartMapper.insert(memberCart);
        }
        MemberCart dbCart = memberCarts.get(0);
        dbCart.setUpdateTime(LocalDateTime.now());
        dbCart.setQuantity(dbCart.getQuantity() + memberCart.getQuantity());
        return memberCartMapper.updateById(dbCart);
    }

    /**
     * 修改购物车
     *
     * @param memberCart 购物车
     * @return 结果
     */
    public int update(MemberCart memberCart) {
        MemberCart cart = memberCartMapper.selectById(memberCart.getId());
        if (cart == null) {
            return 0;
        }
        cart.setQuantity(memberCart.getQuantity());
        cart.setUpdateTime(LocalDateTime.now());
        cart.setUpdateBy(SecurityUtil.getLocalMember().getId());
        return memberCartMapper.updateById(cart);
    }

    public int update(UpdateMemberCartForm form) {
        if (form.getNum() == null || form.getId() == null) {
            throw new ServerException("参数错误");
        }
        Long userId = SecurityUtil.getMemberId();
        LambdaQueryWrapper<MemberCart> qw = new LambdaQueryWrapper<>();
        qw.eq(MemberCart::getMemberId, userId);
        qw.eq(MemberCart::getId, form.getId());
        if (form.getNum() <= 0) {
            return memberCartMapper.delete(qw);
        }
        MemberCart e = new MemberCart();
        e.setQuantity(form.getNum());
        return memberCartMapper.update(e, qw);
    }

    /**
     * 删除购物车信息
     *
     * @param ids 购物车主键
     * @return 结果
     */
    public int deleteByIds(String ids) {
        List<Long> idList = Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        return memberCartMapper.deleteByIds(idList);
    }
}
